
var webResult = require('../web-result');

var db = require('../db');
var jwt = require('jsonwebtoken');
var router = require('express')();


const verifyToken = (request, response, next) => {
    const { token } = request.headers;
    if (!token)
    {
        response.send(webResult.failed(undefined, "权限不足"));
        return;
    }

    try {
        const { id, username } = jwt.decode(token);
        db.query("select * from user where id = ? and username = ?", [id, username])
        .then(res => {
            if (!res[0])
            {
                response.send(webResult.failed(undefined, "不存在的用户"));
                return;
            }
            const password = res[0].password
            jwt.verify(token, password, (err, _data) => {
                if (err)
                {
                    response.send(webResult.failed(undefined, "权限不足"));
                    return;
                }

                next();
            });
        })
    } catch (e) {
        console.error(e);
        response.send(webResult.failed(undefined, "token错误"));
        return;
    }
}


router.all("/upload/*", verifyToken);
router.get("/user/verifyToken", verifyToken);
router.put("/user", verifyToken);
router.post('/article', verifyToken);
router.put('/article', verifyToken);
router.delete('/article', verifyToken);



module.exports = router;




